<?php
class Application_Model_Counter
{
	private $m_cache;
	private $m_strCache;
	private $m_hash = 500;
	private $m_intExpire = 1800;
	private $m_data, $m_offset;

	public function __construct($object, $id)
	{
		$this->m_strObject = $object;
		$this->m_cache = Zend_Registry::get('cache');
		$this->load($id);
	}

	private load($id=NULL)
	{
		if($id !== NULL) $this->m_id = $id;
		$tmp = $this->m_id % $this->m_hash;
		if($this->m_offset != $tmp)
		{
			$this->m_offset = $tmp;
			$this->m_strCache = 'Counter_'.$object.'_'.$this->m_offset;
			if(!$this->m_data = $this->m_cache->load($this->m_strCache))
				$this->m_data = array(
					'time' => time(),
					'items' => array()
				);
		}
	}

	public function get($id=NULL)
	{
		if($id!=NULL) $this->load($id);
		else $id = $this->m_id;
		return isset($this->m_data['items'][$id]) ? $this->m_data['items'][$id] : 0;
	}

	public function set($id, $val)
	{
		$this->m_data['items'][$id] = $val;
		$this->m_cache->save($this->m_data, $this->m_strCache,  array(MEMCACHE_PREF), $this->m_intExpire);
	}

	public function incree()
	{
		$intVal = $this->get()+1;
		$this->set($this->m_id, $intVal);
	}

	public function deleteOffset($offset=NULL)
	{
		$strCache = 'Counter_'.$this->m_strObject.'_'.$offset;
		$this->m_cache->remove($strCache);
	}

	public function getDataOffset($offset=NULL)
	{
		if($offset==NULL) return $this->m_data;
		return $this->m_cache->load('Counter_'.$this->m_strObject.'_'.$offset);
	}
}